﻿#include<iostream>
#include<memory>
#include<functional>
using namespace std;

template<class T>
class shared_ptr
{
public:
	explicit shared_ptr(T* ptr = nullptr)
		: _ptr(ptr)
		, _pcount(new int(1))
	{}

	shared_ptr(const shared_ptr<T>& sp)
		:_ptr(sp._ptr)
		, _pcount(sp._pcount)
	{
		++(*_pcount);
	}

	~shared_ptr()
	{
		release();
	}

	void release()
	{
		if (--(*_pcount) == 0)
		{
			// 最后⼀个管理的对象，释放资源
			delete _ptr;
			delete _pcount;
			_ptr = nullptr;
			_pcount = nullptr;
		}
	}
	
	shared_ptr<T>* operator=(shared_ptr<T>& sp)
	{
		if (sp._ptr != _ptr)
		{
			release();//赋值时如果是最后一个对象就要释放

			_ptr = sp._ptr;
			_pcount = sp._pcount;
			(*_pcount)++;

		}
		return *this;
	}

	T* get() const {
		return _ptr;
	}

	int use_count() const
	{
		return *_pcount;
	}

	T& operator*()
	{
		return *_ptr;
	}

	T* operator->()
	{
		return _ptr;
	}

private:
	T* _ptr;
	int* _pcount;

};

int main()
{
	function<int(int, int)> add = [](int a, int b) {return a + b; };

}